package com.qdaily.ui.ui.views.QDWebView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.ui.controller.ActivityController;
import com.qdaily.ui.data.EventModel.EventQDWebViewLoadComplete;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.ui.WebViewActivity;
import com.qdaily.ui.ui.views.QDWebView.QDArticleWebViewFileCache.QDArticleWebViewFileCacheMgr;
import com.qdaily.ui.util.QDRegUtil;

import java.io.IOException;
import java.io.InputStream;

import com.qdaily.ui.util.BusProvider;
import com.qdaily.ui.util.QDTestServerSetHelper;

/**
 * Created by song on 15/5/4.
 */
public class QDArticleWebViewClient extends WebViewClient{
    private Activity mActivity;
    private QDArticleWebView mWebView;
    private int webViewTopMargin;

    private static final String INJECTION_TOKEN = "qdaily/injection/jsbridge"; //和前端约定的注入位置

    private String TAG = "QDArticleWebViewClient";

    public QDArticleWebViewClient(Activity mActivity)
    {
        super();
        this.mActivity = mActivity;
    }

    public int getWebViewTopMargin() {
        return webViewTopMargin;
    }

    public void setWebViewTopMargin(int webViewTopMargin) {
        this.webViewTopMargin = webViewTopMargin;
    }

    public QDArticleWebView getmWebView() {
        return mWebView;
    }

    public void setmWebView(QDArticleWebView mWebView) {
        this.mWebView = mWebView;
    }

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        QLog.w(TAG, "shouldOverrideUrlLoading:" + url);
        String[] array = QDRegUtil.getQArticleUrlType(url);

        boolean isInnerUrl = false; //符合规则的内链
        if (array != null && array.length == 2)
        {
            String type = array[0];
            int id = Integer.valueOf(array[1]);
            if (id > 0)
            {
                if (type.equals(QDEnum.QUrlEnum.ARTICLE.value) || type.equals(QDEnum.QUrlEnum.CARD.value))
                {
                    ActivityController.DisplayArticle(mActivity, id);
                    isInnerUrl = true;
                }
                else if (type.equals(QDEnum.QUrlEnum.PAPER.value))
                {
                    ActivityController.DisplayVote(mActivity, id);
                    isInnerUrl = true;
                }
                else if (type.equals(QDEnum.QUrlEnum.MOB.value))
                {
                    ActivityController.DisplayMob(mActivity, id);
                    isInnerUrl = true;
                }
            }
        }

        if (!isInnerUrl)
        {
            Intent intent = new Intent(mActivity, WebViewActivity.class);
            intent.putExtra(WebViewActivity.EXTRA_WEBVIEW_URL, url);
            mActivity.startActivity(intent);
        }
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        QLog.w(TAG, "onPageStarted:" + url);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (webViewTopMargin != 0) {
            view.loadUrl("javascript: function setTopMargin() { document.getElementsByTagName(\"body\")[0].style.marginTop = '"+webViewTopMargin+"px';}"
                    +"javascript: setTopMargin()");
        }
        QLog.w(TAG, "onPageFinished:" + url);
        BusProvider.getInstance().post(new EventQDWebViewLoadComplete(mWebView));
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        QLog.w(TAG, "onLoadResource:" + url);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                                      WebResourceRequest request) {
        String url = request.getUrl().toString();
        WebResourceResponse response  = loadFromCache(url);
        if (response == null)
        {
            return super.shouldInterceptRequest(view, request);
        }
        else
        {
            return response;
        }
    }

    public WebResourceResponse shouldInterceptRequest(WebView view,
                                                      String url) {
        WebResourceResponse response  = loadFromCache(url);
        if (response == null)
        {
            return super.shouldInterceptRequest(view, url);
        }
        else
        {
            return response;
        }
    }

    @Nullable
    private WebResourceResponse loadFromCache(String url){
        if (url == null || !url.startsWith("http://"))
            return null;

        Thread a = Thread.currentThread();

        if(url.contains(INJECTION_TOKEN)) {
            return injectJavascriptBridge();
        }

        if (!url.startsWith(QDTestServerSetHelper.getServerIp()))
            return null;

        String mimeType = null;
        if (url.endsWith(QDArticleWebViewFileCacheMgr.QDailyArticleExt))
        {
            mimeType = "text/html";
        }
        else if (url.contains(".png") || url.contains(".jpg") || url.contains(".jpeg") )
        {
            mimeType = "image/jpeg";
        }
        else if (url.contains(".ico"))
        {
            mimeType = "image/x-icon";
        }
        else if (url.contains(".gif"))
        {
            mimeType = "image/gif";
        }
        else if (url.contains(".css"))
        {
            mimeType = "text/css";
        }
        else if (url.contains(".js"))
        {
            mimeType = "application/javascript";
        }

        if (mimeType == null)
        {
            return null;
        }
//此处在主线程
        QLog.w(TAG, a.getId() + "-[loadFromCache]url:" + url + ",mimeType:"+ mimeType);

        WebResourceResponse response = null;

        InputStream localCopy = null;
        try {
            localCopy = QDArticleWebViewFileCacheMgr.getInstance().getLocalCache(url, false);
        } catch (IOException e) {
            Log.e("client", "sss", e);
            e.printStackTrace();
        }
        if (localCopy == null)
        {
            return null;
        }
        else
        {
            return new WebResourceResponse(mimeType, "UTF-8", localCopy);
        }
    }

    @Nullable
    private WebResourceResponse injectJavascriptBridge(){
        QLog.w(TAG, "injectJavascriptBridge start");
        try {
            WebResourceResponse response = new WebResourceResponse(
                    "application/javascript",
                    "UTF8",
                    mActivity.getAssets().open("webviewjavascriptbridge.js")
            );
            return response;
        }
        catch (IOException e) {
            e.printStackTrace(); // Failed to load asset file
            QLog.w(TAG, "injectJavascriptBridge", e);
            return null;
        }
        finally {
            if (mWebView != null)
            {
                mWebView.javascriptBridgeInjectComplete();
            }
        }
    }
}
